package org.hiucung.desktoptranslationtools.viewmodel

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import org.hiucung.desktoptranslationtools.bean.DialogEvent
import org.hiucung.desktoptranslationtools.bean.ExportResult
import org.hiucung.desktoptranslationtools.utils.GradleTranslationHelper
import org.hiucung.desktoptranslationtools.bean.RowResult
import org.hiucung.desktoptranslationtools.bean.Translation
import org.hiucung.desktoptranslationtools.utils.TranslationExcelExporter
import java.io.File

/**
 * @title: ExportViewModel
 * @projectName DesktopTranslationTools
 * @description: 导出 ViewModel
 * @author Kicc
 * @date 2025/7/23 0:36
 */
class ExportViewModel {

    // 导出专用协程
    private val exportJob = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    // 分类完成的翻译，可将写入到表格的数据
    private var translationResult = mutableListOf<RowResult>()

    private val _selectedDirectoryPath = MutableStateFlow<String>("")

    //　翻译所包含的所有国家区域
    private var translationLanguageCodeSet = mutableSetOf<String>()

    val selectedDirectoryPath: StateFlow<String> = _selectedDirectoryPath

    fun updateSelectedDirectory(path: String) {
        _selectedDirectoryPath.value = path
    }

    private val _saveTranslationPath = MutableStateFlow<String>("")

    val saveTranslationPath: StateFlow<String> = _saveTranslationPath

    fun updateSaveTranslationPath(path: String) {
        _saveTranslationPath.value = path
    }

    private val _dialogEvent = MutableSharedFlow<DialogEvent>()

    val dialogEvent = _dialogEvent.asSharedFlow()

    private fun showDialog(event: DialogEvent) {
        exportJob.launch {
            _dialogEvent.emit(event)
        }
    }

    // 在需要显示弹窗的地方调用
    private fun showMessage(message: String) {
        showDialog(DialogEvent.Info(message = message))
    }

    fun showErrorMessage(message: String) {
        showDialog(DialogEvent.Error(message = message))
    }

    // 加载状态（StateFlow 适合持续状态）
    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading

    // 导出结果事件（SharedFlow 适合一次性通知）
    private val _exportEvent = MutableSharedFlow<ExportResult>()
    val exportEvent = _exportEvent.asSharedFlow()

    init {
        exportJob.launch {
            // 默认值是空字符串，因为 StateFlow会马上收到需要过滤
            _selectedDirectoryPath.filter { it.isNotEmpty() }.collect { path ->

                // 拿到项目所有模块名
                val file = File(path)
                val moduleNames =
                    GradleTranslationHelper.extractGradleModuleNames(file)

                // 根据所有 moduleNames拿到对应的 File
                val moduleModuleDirs = if (moduleNames.isNotEmpty()) {
                    file.listFiles { dir, name ->
                        dir.isDirectory && moduleNames.contains(name)
                    }
                } else {
                    file.listFiles { dir ->
                        dir.isDirectory
                    }
                }

                println("开始读取所有module中的翻译资源")

                val translationLocals = mutableListOf<Translation>()
                moduleModuleDirs?.forEach { it ->
                    GradleTranslationHelper.collectTranslationsFromRes(it.name, it).takeIf { it.isNotEmpty() }
                        ?.apply {
                            translationLocals.addAll(this)
                        }
                }

                // 获取所有语言代码
                translationLanguageCodeSet.clear()
                translationLanguageCodeSet = translationLocals.map { it.languageCode }.toSet() as MutableSet<String>

                var message = if (translationLocals.isNotEmpty()) {
                    "读取到了${translationLanguageCodeSet.size}个国家共计:${translationLocals.size}条翻译"
                } else {
                    "找不到翻译资源,确定项目地址没有错误?"
                }
                println(message)

                // 发送一次性事件（非状态）
                showMessage(message)

//                    exportViewModel.updateSelectedDirectory(message)


                translationResult.clear()
                translationResult.addAll(GradleTranslationHelper.processTranslationsByModule(translationLocals))
            }
        }

    }

    // 导出表格
    fun exportToExcel() {
        exportJob.launch {
            _isLoading.value = true
            try {
                TranslationExcelExporter.writeToExcel(
                    translationResult, languages = translationLanguageCodeSet,
                    fileName = File(_saveTranslationPath.value)
                )
                _exportEvent.emit(ExportResult.Success("导出成功！"))
            } catch (e: Exception) {
                _exportEvent.emit(ExportResult.Error("导出失败: ${e.localizedMessage ?: "未知错误"}"))
            } finally {
                _isLoading.value = false
            }
        }
    }
}